package com.youlai.boot.system.converter;

import org.mapstruct.Mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.system.model.entity.Order;
import com.youlai.boot.system.model.form.OrderForm;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 订单管理对象转换器
 *
 * @author zhangyurun
 * @since 2025-03-20 20:33
 */
@Mapper(componentModel = "spring")
public interface OrderConverter {

    @Mapping(target = "area", expression = "java(toAreaList(entity))")
    OrderForm toForm(Order entity);

    @Mappings({
            @Mapping(target = "province", expression = "java(getFirstElement(formData.getArea()))"),
            @Mapping(target = "city", expression = "java(getSecondElement(formData.getArea()))"),
            @Mapping(target = "country", expression = "java(getThirdElement(formData.getArea()))")
    })
    Order toEntity(OrderForm formData);

    default List<String> toAreaList(Order entity) {
        return entity != null ? Arrays.asList(entity.getProvince(), entity.getCity(), entity.getCountry()) : null;
    }

    default String getFirstElement(List<String> area) {
        return Optional.ofNullable(area)
                .flatMap(list -> list.stream().findFirst())
                .orElse(null);
    }

    default String getSecondElement(List<String> area) {
        return Optional.ofNullable(area)
                .flatMap(list -> list.stream().skip(1).findFirst())
                .orElse(null);
    }

    default String getThirdElement(List<String> area) {
        return Optional.ofNullable(area)
                .flatMap(list -> list.stream().skip(2).findFirst())
                .orElse(null);
    }
}